package com.baidu.iit.pxp.parser;

import com.baidu.iit.pxp.constants.BpmnXMLConstants;
import com.baidu.iit.pxp.model.BpmnModel;
import com.baidu.iit.pxp.model.ExtensionAttribute;
import com.baidu.iit.pxp.util.BpmnXMLUtil;
import org.apache.commons.lang3.StringUtils;

import javax.xml.stream.XMLStreamReader;
import java.util.Arrays;
import java.util.List;

/**
 * User: huangweili
 * Date: 14-4-25
 * Time: 下午1:05
 */
public class DefinitionsParser  {

    protected static final List<ExtensionAttribute> defaultAttributes = Arrays.asList(
            new ExtensionAttribute(BpmnXMLConstants.TYPE_LANGUAGE_ATTRIBUTE),
            new ExtensionAttribute(BpmnXMLConstants.EXPRESSION_LANGUAGE_ATTRIBUTE),
            new ExtensionAttribute(BpmnXMLConstants.TARGET_NAMESPACE_ATTRIBUTE)
    );

    public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
        model.setTargetNamespace(xtr.getAttributeValue(null, BpmnXMLConstants.TARGET_NAMESPACE_ATTRIBUTE));
        for (int i = 0; i < xtr.getNamespaceCount(); i++) {
            String prefix = xtr.getNamespacePrefix(i);
            if (prefix != null) {
                model.addNamespace(prefix, xtr.getNamespaceURI(i));
            }
        }

        for (int i = 0; i < xtr.getAttributeCount(); i++) {
            ExtensionAttribute extensionAttribute = new ExtensionAttribute();
            extensionAttribute.setName(xtr.getAttributeLocalName(i));
            extensionAttribute.setValue(xtr.getAttributeValue(i));
            if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) {
                extensionAttribute.setNamespace(xtr.getAttributeNamespace(i));
            }
            if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
                extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
            }
            if (!BpmnXMLUtil.isBlacklisted(extensionAttribute, defaultAttributes)) {
                model.addDefinitionsAttribute(extensionAttribute);
            }
        }
    }
}
